<template>
  <div class="region-manage-container">
    <el-row :gutter="20">
      <!-- 左侧树形区域列表 -->
      <el-col :span="8">
        <el-card class="region-tree-card">
          <template #header>
            <div class="card-header">
              <span>行政区域树</span>
              <div>
                <el-button
                  type="primary"
                  size="small"
                  v-permission="'region:add'"
                  @click="handleAdd"
                >
                  <el-icon><Plus /></el-icon>新增
                </el-button>
                <el-input
                  v-permission="'region:query'"
                  v-model="searchRegion"
                  placeholder="搜索区域"
                  clearable
                  size="small"
                  style="width: 200px; margin-left: 10px"
                />
              </div>
            </div>
          </template>

          <el-tree
            ref="regionTree"
            :data="regionTreeData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            node-key="regionId"
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span>
                {{ node.label }}
                <el-tag
                  v-if="!data.isActive"
                  size="small"
                  type="info"
                  style="margin-left: 10px"
                >
                  已禁用
                </el-tag>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧区域详情 -->
      <el-col :span="16">
        <el-card v-if="currentRegion" class="region-detail-card">
          <template #header>
            <div class="card-header">
              <span>区域详情</span>
              <div>
                <el-button
                  type="primary"
                  size="small"
                  v-permission="'region:edit'"
                  @click="handleEdit"
                >
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  v-permission="'region:delete'"
                  @click="handleDelete"
                  style="margin-left: 10px"
                >
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </div>
            </div>
          </template>

          <el-descriptions :column="2" border>
            <el-descriptions-item label="区域ID">
              {{ currentRegion.regionId }}
            </el-descriptions-item>
            <el-descriptions-item label="区域名称">
              {{ currentRegion.regionName }}
            </el-descriptions-item>
            <el-descriptions-item label="区域层级">
              {{ getLevelName(currentRegion.regionLevel) }}
            </el-descriptions-item>
            <el-descriptions-item label="行政区划代码">
              {{ currentRegion.regionCode || '暂无' }}
            </el-descriptions-item>
            <el-descriptions-item label="上级区域">
              {{ currentRegion.parentName || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-switch
                v-permission="'region:status'"
                v-model="currentRegion.isActive"
                :active-value="1"
                :inactive-value="0"
                @change="
                  () =>
                    handleStatusChange(
                      currentRegion.regionId,
                      currentRegion.isActive
                    )
                "
              />
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-empty v-else description="请选择区域" />
      </el-col>
    </el-row>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form
        ref="regionForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="区域名称" prop="regionName">
          <el-input
            v-model="formData.regionName"
            placeholder="请输入区域名称"
          />
        </el-form-item>
        <el-form-item label="上级区域" prop="parentId">
          <el-cascader
            v-model="formData.parentId"
            :options="regionOptions"
            :props="cascaderProps"
            :show-all-levels="false"
            clearable
            placeholder="请选择上级区域"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="区域层级" prop="regionLevel">
          <el-select
            v-model="formData.regionLevel"
            placeholder="请选择区域层级"
            style="width: 100%"
          >
            <el-option label="国家" :value="1" />
            <el-option label="省/州" :value="2" />
            <el-option label="市" :value="3" />
            <el-option label="区/县" :value="4" />
            <el-option label="乡镇/街道" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="行政区划代码" prop="regionCode">
          <el-input
            v-model="formData.regionCode"
            placeholder="请输入行政区划代码"
          />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-radio-group v-model="formData.isActive">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getRegionTree,
  getRegionDetail,
  addRegion,
  updateRegion,
  deleteRegion,
  changeRegionStatus
} from '@/api/regions'

// 树形数据
const regionTreeData = ref([])
const searchRegion = ref('')
const currentRegion = ref(null)
const regionTree = ref(null)
// 当前已展开的节点 key 列表
const expandedKeys = ref([])

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)

// 表单数据
const formData = reactive({
  regionId: null,
  parentId: null,
  regionName: '',
  regionLevel: 1,
  regionCode: '',
  isActive: 1
})

// 表单验证规则
const rules = reactive({
  regionName: [
    { required: true, message: '请输入区域名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  regionLevel: [
    { required: true, message: '请选择区域层级', trigger: 'change' }
  ]
})
// 定义树子数据
const defaultProps = {
  children: 'children',
  label: 'regionName'
}
// 级联选择器配置
const cascaderProps = {
  value: 'regionId',
  label: 'regionName',
  children: 'children',
  checkStrictly: true,
  emitPath: false
}

// 区域层级映射
const levelMap = {
  1: '国家',
  2: '省/州',
  3: '市',
  4: '区/县',
  5: '乡镇/街道'
}

// 计算属性 - 用于级联选择器的选项
const regionOptions = computed(() => {
  return regionTreeData.value
})
// 查找父级区域名称
const getParentName = (parentId) => {
  if (!parentId) return '无'

  const findNode = (nodes) => {
    for (const node of nodes) {
      if (node.regionId === parentId) {
        return node.regionName
      }
      if (node.children) {
        const result = findNode(node.children)
        if (result) return result
      }
    }
    return null
  }

  return findNode(regionTreeData.value) || '未知'
}
// 获取区域层级名称
const getLevelName = (level) => levelMap[level] || '未知'

// 加载区域树数据
const loadRegionTree = async () => {
  try {
    const res = await getRegionTree()
    regionTreeData.value = res.data.data
  } catch (error) {
    console.error('加载区域树失败', error)
  }
}

// 搜索过滤节点
const filterNode = (value, data) => {
  if (!value) return true
  return data.regionName.includes(value)
}

// 点击树节点处理
const handleNodeClick = async (data, node) => {
  try {
    const res = await getRegionDetail(data.regionId)
    const region = res.data.data

    // 动态添加 parentName 字段
    region.parentName = getParentName(region.parentId)
    currentRegion.value = region

    // 如果是第三级（市），则只展开第四级（区/县）
    if (data.regionLevel === 3) {
      const children = node.expanded
        ? []
        : data.children?.map((c) => c.regionId) || []
      expandedKeys.value = [...new Set([...expandedKeys.value, ...children])]
    } else {
      // 其他情况按需展开
      if (node.expanded) {
        expandedKeys.value = expandedKeys.value.filter(
          (key) => key !== data.regionId
        )
      } else {
        expandedKeys.value.push(data.regionId)
      }
    }

    // 更新 tree 的展开状态
    regionTree.value.updateKey() // 强制更新树状态（可选）
  } catch (error) {
    console.error('获取区域详情失败', error)
  }
}

// 新增区域
const handleAdd = () => {
  dialogTitle.value = '新增区域'
  isAdd.value = true
  resetForm()
  dialogVisible.value = true
}

// 编辑区域
const handleEdit = () => {
  dialogTitle.value = '编辑区域'
  isAdd.value = false
  Object.assign(formData, currentRegion.value)
  dialogVisible.value = true
}

// 删除区域
const handleDelete = () => {
  ElMessageBox.confirm('确认删除该区域吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(async () => {
      await deleteRegion(currentRegion.value.regionId)

      // 删除成功
      ElMessage.success('删除成功')
      loadRegionTree()
      currentRegion.value = null
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}
// 状态切换
const handleStatusChange = async (regionId, isActive) => {
  try {
    await changeRegionStatus(regionId, isActive)
    ElMessage.success('状态更新成功')
    loadRegionTree()
  } catch (error) {
    // 请求失败，恢复原来的状态
    currentRegion.value.isActive = isActive === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 重置表单
const resetForm = () => {
  formData.regionId = null
  formData.regionName = ''
  formData.regionLevel = 1
  formData.regionCode = ''
  formData.isActive = 1
}

// 提交表单
const submitForm = async () => {
  try {
    if (isAdd.value) {
      await addRegion(formData)
      ElMessage.success('新增成功')
    } else {
      await updateRegion(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    loadRegionTree()
  } catch (error) {
    console.error(error)
  }
}

// 初始化加载数据
onMounted(() => {
  loadRegionTree()
})

// 监听搜索
watch(searchRegion, (val) => {
  regionTree.value.filter(val)
})
</script>

<style scoped>
.delete-confirm-button {
  background-color: #f56c6c !important; /* 红色背景 */
  border-color: #f56c6c !important;
}

.delete-confirm-button:hover {
  background-color: #e05c5c !important;
}

.delete-cancel-button {
  margin-left: 20px; /* 增加取消按钮左边距 */
}
.region-manage-container {
  background-color: #f5f7fa;
  padding: 20px;
  height: calc(100vh - 84px);
}

.region-tree-card,
.region-detail-card {
  height: calc(100vh - 124px);
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
